<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit" :selfUpdate="true">
        <a-tabs :activeKey="tabKey" :tabBarStyle="{marginBottom: '30px'}" @change="handleTabs">
          <a-tab-pane :key="0" tab="基本信息"></a-tab-pane>
          <a-tab-pane :key="1" tab="规格/库存"></a-tab-pane>
          <a-tab-pane :key="2" tab="服务详情"></a-tab-pane>
          <a-tab-pane :key="3" tab="更多设置"></a-tab-pane>
        </a-tabs>
        <div class="tabs-content">
          <!-- 基本信息 -->
          <div class="tab-pane" v-show="tabKey == 0">
            <a-form-item label="服务名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="请输入服务名称"
                v-decorator="['goods_name', {rules: [{required: true, min: 2, message: '请输入至少2个字符'}]}]"
              />
            </a-form-item>
            <a-form-item label="服务分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="['category_id', { initialValue: -1, rules: [{ required: true, message: '请选择服务分类' }]}]">
                <a-select-option :value="-1">请选择</a-select-option>
                <a-select-option
                  v-for="(item, index) in formData.categoryList"
                  :key="index"
                  :value="item.value"
                >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="!isAdd" label="所属分店" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select @change="addressChange" v-decorator="['address_id', { initialValue: -1, rules: [{ required: true, message: '请选择所属分店' }]}]">
                <a-select-option :value="-1">请选择</a-select-option>
                <a-select-option
                  v-for="(item, index) in formData.addressList"
                  :key="index"
                  :value="item.value"
                >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="服务技师" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree-select
                placeholder="请选择服务技师"
                :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                :treeData="formData.proficientList"
                treeCheckable
                treeCheckStrictly
                allowClear
                v-decorator="['proficient', { rules: [{required: true, message: '请至少选择1个服务技师'}]}]"
              ></a-tree-select>
            </a-form-item>
            <a-form-item
              label="技师价格"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="价格顺序与选择技师顺序必须一一对应，价格之间以英文逗号 , 分开">
              <a-input
                placeholder="请输入技师价格"
                v-decorator="['proficient_price', {rules: [{required: true, message: '请输入技师价格'}]}]"
              />
            </a-form-item>
            <a-form-item
              label="服务图片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="建议尺寸：750*750像素, 最多上传10张, 可拖拽图片调整顺序, 第1张将作为服务首图"
            >
              <SelectImage
                multiple
                :maxNum="10"
                :defaultList="formData.goods.goods_images ? formData.goods.goods_images : []"
                v-decorator="['imagesIds', {rules: [{required: true, message: '请至少上传1张服务图片'}]}]"
              />
            </a-form-item>
            <a-form-item label="服务类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group
                v-decorator="['service_type', {initialValue: 10, rules: [{ required: true }]}]"
              >
                <a-radio :value="10">仅到店</a-radio>
                <a-radio :value="20">仅上门</a-radio>
                <a-radio :value="30">到店+上门</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="服务状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group
                v-decorator="['status', {initialValue: 10, rules: [{ required: true }]}]"
              >
                <a-radio :value="10">上架</a-radio>
                <a-radio :value="20">下架</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="服务排序" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="数字越小越靠前">
              <a-input-number
                :min="0"
                v-decorator="['sort', {initialValue: 100, rules:[{ required: true }]}]"
              />
            </a-form-item>
          </div>

          <!-- 规格/库存 -->
          <div class="tab-pane" v-show="tabKey == 1">
            <a-form-item label="规格类型" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="订单价格=服务价格+技师价格">
              <a-radio-group
                v-decorator="['spec_type', { initialValue: 10, rules: [{ required: true }] }]"
                @change="onForceUpdate()"
              >
                <a-radio :value="10">单规格</a-radio>
                <a-radio :value="20">多规格</a-radio>
              </a-radio-group>
            </a-form-item>
            <!-- 多规格的表单内容 -->
            <div v-show="form.getFieldValue('spec_type') == 20">
              <MultiSpec
                :defaultSpecList="formData.goods.specList"
                :defaultSkuList="formData.goods.skuList"
                ref="MultiSpec" />
            </div>
            <!-- 单规格的表单内容 -->
            <div v-show="form.getFieldValue('spec_type') == 10">
              <a-form-item
                label="服务价格"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                extra="服务的实际购买金额，最低0.01"
              >
                <a-input-number
                  :min="0.01"
                  :precision="2"
                  v-decorator="['goods_price', { initialValue: 1, rules: [{ required: true, message: '请输入服务价格' }] }]"
                />
                <span class="ml-10">元</span>
              </a-form-item>
              <a-form-item
                label="划线价"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                extra="划线价仅用于服务页展示"
              >
                <a-input-number :min="0" :precision="2" v-decorator="['line_price']" />
                <span class="ml-10">元</span>
              </a-form-item>
              <!--              <a-form-item-->
              <!--                label="当前库存数量"-->
              <!--                :labelCol="labelCol"-->
              <!--                :wrapperCol="wrapperCol"-->
              <!--                extra="服务的实际库存数量，为0时用户无法下单"-->
              <!--              >-->
              <!--                <a-input-number-->
              <!--                  :min="0"-->
              <!--                  :precision="0"-->
              <!--                  v-decorator="['stock_num', { initialValue: 100, rules:[{ required: true, message: '请输入库存数量' }] }]"-->
              <!--                />-->
              <!--                <span class="ml-10">件</span>-->
              <!--              </a-form-item>-->
            </div>
            <!--            <a-form-item label="库存计算方式" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
            <!--              <a-radio-group-->
            <!--                v-decorator="['deduct_stock_type', {initialValue: 10, rules: [{ required: true }]}]"-->
            <!--              >-->
            <!--                <a-radio :value="10">下单减库存</a-radio>-->
            <!--                <a-radio :value="20">付款减库存</a-radio>-->
            <!--              </a-radio-group>-->
            <!--            </a-form-item>-->
          </div>

          <!-- 服务详情 -->
          <div class="tab-pane" v-show="tabKey == 2">
            <a-form-item label="服务详情" :labelCol="labelCol" :wrapperCol="{span: 16}">
              <Ueditor v-decorator="['content', {rules: [{required: true, message: '服务详情不能为空'}]}]" />
            </a-form-item>
          </div>

          <!-- 更多设置 -->
          <div class="tab-pane" v-show="tabKey == 3">
            <a-form-item
              label="服务卖点"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="一句话简述，例如：此款服务美观大方 性价比较高 不容错过"
            >
              <a-input placeholder="请输入服务卖点" v-decorator="['selling_point']" />
            </a-form-item>
            <a-form-item
              label="初始销量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="用户端展示的销量 = 初始销量 + 实际销量"
            >
              <a-input-number v-decorator="['sales_initial', {initialValue: 0}]" />
            </a-form-item>
            <a-form-item
              label='黄金会员折扣'
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              extra='黄金会员打折折扣'
            >
              <a-input-number :min='1' :max='10' v-decorator="['first', {initialValue: 10}]" />
            </a-form-item>

            <a-form-item
              label='铂金会员折扣'
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              extra='铂金会员打折折扣'
            >
              <a-input-number :min='1' :max='10' v-decorator="['second', {initialValue: 10}]" />
            </a-form-item>

            <a-form-item
              label='钻石会员折扣'
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              extra='钻石会员打折折扣'
            >
              <a-input-number :min='1' :max='10' v-decorator="['third', {initialValue: 10}]" />
            </a-form-item>

            <a-form-item
              label='黑金会员折扣'
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              extra='黑金会员打折折扣'
            >
              <a-input-number :min='1' :max='10' v-decorator="['fouth', {initialValue: 1}]" />
            </a-form-item>
          </div>
        </div>
        <a-form-item class="mt-20" :wrapper-col="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit" :loading="isBtnLoading">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import * as GoodsApi from '@/api/goods'
import { SelectImage, Ueditor, InputNumberGroup } from '@/components'
import GoodsModel from '@/common/model/goods/Index'
import MultiSpec from './modules/MultiSpec'
import { isEmptyObject } from '@/utils/util'
import * as Store from '@/api/store'

export default {
  components: {
    SelectImage,
    Ueditor,
    InputNumberGroup,
    MultiSpec
  },
  data () {
    return {
      // 默认的标签索引
      tabKey: 0,
      // 标签布局属性
      labelCol: { span: 3 },
      // 输入框布局属性
      wrapperCol: { span: 10 },
      // loading状态
      isAdd: false,
      isLoading: false,
      isBtnLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 服务ID
      goodsId: null,
      // 表单数据
      formData: GoodsModel.formData
    }
  },
  created () {
    // 初始化数据
    this.storeInfo()
    this.initData()
  },
  beforeDestroy () {
    // 销毁服务详情
    GoodsModel.formData.goods = {}
  },
  methods: {
    storeInfo() {
      Store.info().then((result) => {
        const { data: { storeInfo } } = result
        this.isAdd = storeInfo.isAdd
        if (storeInfo.isAdd) {
          GoodsModel.getProficientList(storeInfo.address_id)
        }
      })
    },
    addressChange(value, option) {
      this.formData.proficientList = []
      GoodsModel.getProficientList(value)
      return new Promise((resolve, reject) => {
        resolve(true)
      })
    },
    // 初始化数据
    initData () {
      // 记录服务ID
      this.goodsId = this.$route.query.goodsId
      // 获取form所需的数据
      this.isLoading = true
      GoodsModel.getFromData(this.goodsId)
        .then(() => {
          // 服务表单数据
          if (!isEmptyObject(this.form.getFieldsValue())) {
            this.addressChange(GoodsModel.getFieldsValue().address_id)
              .then((res) => {
                res && this.form.setFieldsValue(GoodsModel.getFieldsValue())
              })
          }
          this.isLoading = false
        })
    },

    // 手动强制更新页面
    onForceUpdate (bool = false) {
      this.$forceUpdate()
      // bool为true时再执行一次 $forceUpdate, 特殊情况下需执行两次，原因如下：
      // 第一次执行 $forceUpdate时, 新元素绑定v-decorator无法获取到form.getFieldValue
      bool && setTimeout(() => {
        this.$forceUpdate()
      }, 10)
    },

    // 切换tab选项卡
    handleTabs (key) {
      this.tabKey = key
    },

    // 刷新分类列表
    onReloadCategoryList () {
      this.isLoading = true
      GoodsModel.getCategoryList().then(() => {
        this.isLoading = false
      })
    },

    // 刷新服务与承诺列表
    onReloadServiceList () {
      this.isLoading = true
      GoodsModel.getServiceList().then(() => {
        this.isLoading = false
      })
    },

    // 刷新配送模板列表
    onReloadDeliveryList () {
      this.isLoading = true
      GoodsModel.getDeliveryList().then(() => {
        this.isLoading = false
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 定位到错误的tab选项卡
        if (errors) {
          this.onTargetTabError(errors)
          return false
        }
        // 验证多规格
        if (values.spec_type === 20) {
          const MultiSpec = this.$refs.MultiSpec
          if (!MultiSpec.verifyForm()) {
            this.tabKey = 1
            return false
          }
          // 记录多规格数据
          values.specData = MultiSpec.getFromSpecData()
        }
        // 提交到后端api
        this.onFormSubmit(values)
        return true
      })
    },

    /**
     * 定位到错误的tab选项卡
     */
    onTargetTabError (errors) {
      // 表单字段与tabKey对应关系
      // 只需要必填字段就可
      const tabsFieldsMap = [
        ['goods_name', 'categorys', 'imagesIds', 'delivery_id'],
        ['spec_type', 'goods_price'],
        ['content'],
        ['alone_grade_equity', 'first_money', 'second_money', 'third_money']
      ]
      const field = Object.keys(errors).shift()
      for (const key in tabsFieldsMap) {
        if (tabsFieldsMap[key].indexOf(field) > -1) {
          this.tabKey = parseInt(key)
          break
        }
      }
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.isLoading = true
      this.isBtnLoading = true
      GoodsApi.edit({ goodsId: this.goodsId, form: values })
        .then(result => {
          // 显示提示信息
          this.$message.success(result.message, 1.5)
          // 跳转到列表页
          setTimeout(() => {
            this.$router.push('./index')
          }, 1500)
        })
        .catch(() => {
          this.isBtnLoading = false
        })
        .finally(() => {
          this.isLoading = false
        })
    }

  }
}

</script>
<style lang="less" scoped>
@import './style.less';
</style>
